<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/9/25 15:07
 */

namespace module\user\controller;

use module\user\library\UserController;

use app\library\validate\EnumValidate;
use module\user\enum\CaptchaEmsEventEnum;
use module\user\enum\CaptchaSmsEventEnum;
use module\user\logic\PassportLogic;
use mof\ApiResponse;
use mof\exception\LogicException;
use think\response\Json;

class Captcha extends UserController
{
    /**
     * 发送邮件验证码
     * @param PassportLogic $logic
     * @return Json
     */
    public function ems(PassportLogic $logic): Json
    {
        EnumValidate::register();
        $post = $this->request->withValidate([
            'email|邮箱' => 'require|email',
            'event|事件' => 'require|enum:' . CaptchaEmsEventEnum::class,
        ])->post();

        $event = CaptchaEmsEventEnum::from($post['event']);
        if (!$this->auth->isLogin() && $event->needLogin()) {
            return ApiResponse::needLogin();
        } else if (!$event->isEnabled()) {
            throw new LogicException('未开启邮箱验证码行为');
        }

        $logic->sendCaptchaByEmail($post['email'], $post['event']);
        return ApiResponse::success();
    }

    public function sms(PassportLogic $logic): Json
    {
        EnumValidate::register();
        $post = $this->request->withValidate([
            'mobile|手机号' => 'require|mobile',
            'event|事件'    => 'require|enum:' . CaptchaSmsEventEnum::class,
        ])->post();

        $event = CaptchaSmsEventEnum::from($post['event']);
        if (!$this->auth->isLogin() && $event->needLogin()) {
            return ApiResponse::needLogin();
        } else if (!$event->isEnabled()) {
            throw new LogicException('未开启短信验证码行为');
        }

        $logic->sendCaptchaBySms($post['mobile'], $post['event']);
        return ApiResponse::success();
    }
}